﻿using CPPEI.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XWeb.WebApi.Menu
{
    [GetAction("menu", "get", "1.0")]
    public class GetAction : BaseAction<GetParams, GetResult>
    {
        protected override ActionResult<GetResult> OnExecute(ActionContext context, SysParams sysParams, GetParams opParams)
        {
            GetResult actResult = new GetResult();

            foreach (XWeb.Core.Data.Menu menu in XWeb.Core.Cache.CurrentApp.Menus)
            {
                actResult.Items.Add(ConvertSubs(menu));
            }

            return new ActionResult<GetResult>(actResult);
        }

        private GetResult.Item ConvertSubs(XWeb.Core.Data.Menu menu)
        {
            GetResult.Item item = new GetResult.Item();
            item.Caption = menu.Name;
            item.Icon = menu.Icon;
            item.LinkUrl = string.Format("{0}{1}", XWeb.Core.Cache.CurrentApp.BaseUrl, menu.Url);

            foreach (XWeb.Core.Data.Menu subMenu in menu.Children)
            {
                item.Items.Add(ConvertSubs(subMenu));
            }

            return item;
        }
    }

    public class GetParams
    {
    }

    public class GetResult
    {
        public List<Item> Items { get; set; }

        public GetResult()
        {
            Items = new List<Item>();
        }

        public class Item
        {
            public string Caption { get; set; }
            public string Icon { get; set; }

            public string LinkUrl { get; set; }

            public List<Item> Items { get; set; }

            public Item()
            {
                Items = new List<Item>();
            }
        }
    }
}
